#include "UserLatestMsgNumNotify.h"
#include "Request/RquestType.h"
#include "Request/HandleRequest.h"

UserLatestMsgNumNotify::UserLatestMsgNumNotify(int user_id):user_id(user_id){

}

UserLatestMsgNumNotify::UserLatestMsgNumNotify(const json& user_latest_msg_num_notify_json){
    this->unserialize(user_latest_msg_num_notify_json);
}

json UserLatestMsgNumNotify::serialize() const {
    json j;
    j["user_id"] = this->user_id;
    json latest_msg_num_notify_json_array=json::array();
    for(const auto&[chat_room_id, latest_msg_num_notify]:this->latest_msg_num_notify_map){
        latest_msg_num_notify_json_array.push_back(latest_msg_num_notify.serialize());
    }
    j["latest_msg_num_notify_map"] = latest_msg_num_notify_json_array;
    return j;
}

void UserLatestMsgNumNotify::unserialize(const json& j) {
    this->user_id = j["user_id"];
    json latest_msg_num_notify_json_array=j["latest_msg_num_notify_map"];
    for(const auto&latest_msg_num_notify_json:latest_msg_num_notify_json_array){
        LatestMsgNumNotify latest_msg_num_notify(latest_msg_num_notify_json);
        this->latest_msg_num_notify_map[latest_msg_num_notify.get_chat_room_id()]=latest_msg_num_notify;
    }
}

void UserLatestMsgNumNotify::send_latest_msg_num(int socket_fd){
    json response;
    response["response_type"]=LATEST_MSG_NUM_NOTIFY;
    response["result"]=0;
    response["msg"]="最新消息通知";
    json user_latest_msg_num_notify_json=this->serialize();
    response["user_latest_msg_num_notify"]=user_latest_msg_num_notify_json;
    ResponseClient(socket_fd,response);
}

void UserLatestMsgNumNotify::add_one_num(string chat_room_id, string time){
    if(this->latest_msg_num_notify_map.find(chat_room_id)!=this->latest_msg_num_notify_map.end()){
        this->latest_msg_num_notify_map[chat_room_id].add_one_num(time);
    }else{
        LatestMsgNumNotify latest_msg_num_notify(chat_room_id,1,time);
        this->latest_msg_num_notify_map[chat_room_id]=latest_msg_num_notify;
    }
}